/*
 * Copyright (C) 2009 JavaRosa
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.pih.javarosa.activity.select;

import java.util.Random;
import java.util.Vector;

import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.entity.model.Entity;
//import org.javarosa.patient.model.Patient;
import org.pih.javarosa.model.Drug;

public class DrugEntity extends Entity<Drug> {
	protected String ID;
	protected String name;
	protected String protocolXFormPath;
		
	protected String[] normalizedName;
	protected String normalizedID;
	
	public DrugEntity factory () {
		return new DrugEntity();
	}
	
	public String entityType() {
		return "Drug";
	}

	public void loadEntity(Drug drug) {
		ID = ExtUtil.emptyIfNull("" + drug.getID());
		name = ExtUtil.emptyIfNull(drug.getName());
		protocolXFormPath = ExtUtil.emptyIfNull(drug.getProtocolXFormPath());
		
		normalizedName = normalizeNames();
		normalizedID = normalizeID(getID());
	}
	
	public String getID() {
		return ID;
	}

	public String getName() {
		return name;
	}
	
	public String getProtocolXFormPath() {
		return protocolXFormPath;
	}
	
	protected static String normalizeID (String ID) {
		StringBuffer sb = new StringBuffer();
		char[] carr = ID.toCharArray();
		
		for (int i = 0; i < carr.length; i++) {
			char c = carr[i];
			if (Character.isDigit(c) || Character.isLowerCase(c) || Character.isUpperCase(c)) {
				if (Character.isLowerCase(c))
					c = Character.toUpperCase(c);
				sb.append(c);
			}
		}
			
		return sb.toString();
	}
	
	protected static Vector normalizeName (String name) {
		StringBuffer sb = new StringBuffer();
		char[] carr = name.toCharArray();
		
		for (int i = 0; i < carr.length; i++) {
			char c = carr[i];
			if (Character.isDigit(c) || Character.isLowerCase(c) || Character.isUpperCase(c)) {
				if (Character.isLowerCase(c))
					c = Character.toUpperCase(c);
				sb.append(c);
		//	} else if (c == '\'' || c == '-') {
		//		//do nothing
			} else {
				sb.append(' ');
			}
		}
			
		return DateUtils.split(sb.toString(), " ", true);
	}
	
	protected static boolean findKey (String str, String key, boolean anywhere) {
		if (str.length() == 0 || key.length() == 0) {
			return false;
		} else {
			if (anywhere) {
				return (str.indexOf(key) != -1);
			} else {
				return str.startsWith(key);
			}
		}
	}
	
	public boolean match (String key) {
		return matchID(key) || matchName(key);
	}
	
	public boolean matchID(String key) {
		String normalizedKey = normalizeID(key);
		
		return findKey(normalizedID, normalizedKey, false);
	}

	protected void concatVector (Vector base, Vector append) {
		for (int i = 0; i < append.size(); i++)
			base.addElement(append.elementAt(i));
	}
	
	protected String[] normalizeNames () {
		Vector nameFrags = new Vector();
		
		String[] nameNorm = new String[nameFrags.size()];
		for (int i = 0; i < nameNorm.length; i++)
			nameNorm[i] = (String)nameFrags.elementAt(i);
		return nameNorm;
	}
	
	public boolean matchName(String key) {
		Vector keyFrags = normalizeName(key);
		
		for (int i = 0; i < keyFrags.size(); i++) {
			String keyFrag = (String)keyFrags.elementAt(i);
			boolean fragMatched = false;
			for (int j = 0; j < normalizedName.length; j++) {
				String nameFrag = normalizedName[j];
				if (findKey(nameFrag, keyFrag, false)) {
					fragMatched = true;
					break;
				}
			}
			if (!fragMatched) {
				return false;
			}
		}
		return true;
	}

	public String[] getHeaders(boolean detailed) {
		//#if javarosa.patientselect.formfactor == nokia-s40
		//# String[] shortHeaders = {"Name", "ID"};
		//#else
		String[] shortHeaders = {"Name", "ID"};
		//#endif

		String[] longHeaders = {"Name", "ID", "XForm"};
		
		return detailed ? longHeaders : shortHeaders;
	}

	public String[] getShortFields() {
		String[] fields = new String[getHeaders(false).length];
		fields[0] = getName();
		fields[1] = getID();
		
		return fields;
	}

	public String[] getLongFields(Drug p) {
		String[] fields = new String[getHeaders(true).length];
	
		Random r = new Random();
		
		fields[0] = getName();
		fields[1] = getID();
		fields[2] = getProtocolXFormPath();
		
		return fields;
	}
	
	public String[] getSortFields () {
		return new String[] {"NAME", "ID"};
	}
	
	public String[] getSortFieldNames () {
		return new String[] {"Name", "ID"};
	}
		
	public Object getSortKey (String fieldKey) {
		if (fieldKey.equals("NAME")) {
			return getName();
		} else if (fieldKey.equals("ID")) {
			return getID();
		} else {
			throw new RuntimeException("Sort Key [" + fieldKey + "] is not supported by this entity");
		}
	}

}
